package com.next.aappublicapp.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.Signature;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;

import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.NewPermissionsRequest;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.google.gson.Gson;

public class FacebookUtil {

	private static final String FACEBOOK_FIRST_TIME_CACHE = "FFTC";
	private static final String ALREADY_POSTED_KEY = "AlreadyPosted";
	private static final String ALREADY_POSTED_KEY_YES = "Yes";
	private static final String FACEBOOK_USER_ID = "FACEBOOK_USER_ID";
	private static final String FACEBOOK_USER = "FACEBOOK_USER";
	/**
	 * @param args
	 */
	public static boolean checkReadPermission(Activity activity, List<String> permissions) {
		try{
			Log.i("Ravi", "Checking for permission " + permissions);
			Log.i("Ravi", "Session.getActiveSession().getPermissions() "
					+ Session.getActiveSession().getPermissions());
			if (Session.getActiveSession().getPermissions().containsAll(permissions)) {
				// We can do the action right away.
				// handlePendingAction();
				Log.i("Ravi", "User have given permission " + permissions);
				return true;
			} else {
				Log.i("Ravi", "User DO NOT have given permission " + permissions);
				// We need to reauthorize, then complete the action when we get
				// called back.
				List<String> allPermissions = new ArrayList<String>();
				allPermissions.addAll(permissions);
				NewPermissionsRequest newPermissionsRequest = new NewPermissionsRequest(
						activity, allPermissions);
				Session.getActiveSession().requestNewReadPermissions(newPermissionsRequest);
			}

		}catch(Exception ex){
			ex.printStackTrace();
		}
		return Session.getActiveSession().getPermissions().contains(permissions);
	}
	/**
	 * @param args
	 */
	public static boolean checkPermission(Activity activity, String permission) {
		try{
			Log.i("Ravi", "Checking for permission " + permission);
			Log.i("Ravi", "Session.getActiveSession().getPermissions() "
					+ Session.getActiveSession().getPermissions());
			if (Session.getActiveSession().getPermissions().contains(permission)) {
				// We can do the action right away.
				// handlePendingAction();
				return true;
			} else {
				// We need to reauthorize, then complete the action when we get
				// called back.
				List<String> allPermissions = new ArrayList<String>();
				allPermissions.add(permission);
				NewPermissionsRequest newPermissionsRequest = new NewPermissionsRequest(
						activity, allPermissions);
				Session.getActiveSession().requestNewPublishPermissions(
						newPermissionsRequest);
			}

		}catch(Exception ex){
			ex.printStackTrace();
		}
		return true;
	}

	public static boolean isFacebookLoggedIn() {
		if (Session.getActiveSession() == null) {
			Log.i("Ravi", "isFacebookLoggedIn = false" );
			return false;
		}
		Log.i("Ravi", "isFacebookLoggedIn = "+Session.getActiveSession().isOpened() );
		boolean sessionOpen = Session.getActiveSession().isOpened();
		return sessionOpen;
	}
	
	public static void saveFaceookUserId(Activity activity,String facebookUserId){
			final SharedPreferences prefs = activity.getSharedPreferences(FACEBOOK_FIRST_TIME_CACHE, Context.MODE_PRIVATE);
			String existingFacebookUserId = prefs.getString(FACEBOOK_USER_ID, null);
			if(existingFacebookUserId == null || !existingFacebookUserId.equals(facebookUserId)){
				Editor editor = prefs.edit();
				editor.putString(FACEBOOK_USER_ID, facebookUserId);
				editor.commit();
			}
	}
	public static void saveFaceookUser(Activity activity,GraphUser graphUser){
		try{
			final SharedPreferences prefs = activity.getSharedPreferences(FACEBOOK_FIRST_TIME_CACHE, Context.MODE_PRIVATE);
			Editor editor = prefs.edit();
			Gson gson = new Gson();
			String jsonString = gson.toJson(graphUser);
			editor.putString(FACEBOOK_USER, jsonString);
			editor.commit();
		}catch(Exception ex){
			ex.printStackTrace();
		}
}
	
	public static String getFaceookUserId(Context context){
		final SharedPreferences prefs = context.getSharedPreferences(FACEBOOK_FIRST_TIME_CACHE, Context.MODE_PRIVATE);
		String facebookUserId = prefs.getString(FACEBOOK_USER_ID, null);
		return facebookUserId;
}

	public static void publishFirstTimeInstallMessage(Activity activity) {
		Log.i("Facebook", "publishFirstTimeInstallMessage : isFacebookLoggedIn");
		if(!isFacebookLoggedIn()){
			return;
		}
		final SharedPreferences prefs = activity.getSharedPreferences(
				FACEBOOK_FIRST_TIME_CACHE, Context.MODE_PRIVATE);
		String allreadyPosted = prefs.getString(ALREADY_POSTED_KEY, "NO");
		Log.i("Facebook", "publishFirstTimeInstallMessage : allreadyPosted="+allreadyPosted);
		if (allreadyPosted.equals(ALREADY_POSTED_KEY_YES)) {
			Log.i("Ravi", "Already Published so not doing it again " + Session.getActiveSession());
			return;
		}
		boolean permisison = checkPermission(activity, "publish_stream");
		Log.i("Facebook", "publishFirstTimeInstallMessage : permisison="+permisison);
		if(permisison){
			Log.i("Facebook", "publishFirstTimeInstallMessage Publishing " + Session.getActiveSession());
			Bundle postParams = new Bundle();
			postParams.putString("name", "Aam Aadmi Party Mobile Application for Android");
			postParams.putString("caption", "I Just installed this Mobile App.");
			postParams
					.putString(
							"description",
							"Friend AAP is going mobile now, install the Android Mobile Application and connect to Aam Aadmi Party in real time for latest News/Videos/Facebook updates");
			postParams.putString("link", "https://play.google.com/store/apps/details?id=com.next.aappublicapp");
			postParams
					.putString(
							"picture",
							"https://lh3.googleusercontent.com/-v1OsSQJ6AFs/UaDpPW43uEI/AAAAAAAALnA/DmSSij7tKgE/s512-no/ic_launcher-web.png");

			Request.Callback callback = new Request.Callback() {
				public void onCompleted(Response response) {
					Log.i("Facebook", "publishFirstTimeInstallMessage response " + response);
					/*
					Log.i("Ravi", "graph " + response.getGraphObject());
					JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
					
					String postId = null;
					try {
						postId = graphResponse.getString("id");
					} catch (JSONException e) {
						Log.i("Ravi", "JSON error " + e.getMessage());
					}
					*/
					FacebookRequestError error = response.getError();
					Log.i("Facebook", "publishFirstTimeInstallMessage error " + error);
					if (error != null) {
						/*
						 * Toast.makeText(MainActivity.this
						 * .getApplicationContext(), error.getErrorMessage(),
						 * Toast.LENGTH_SHORT).show();
						 */
					} else {
						Log.i("Facebook", "Succesfully posted on user TimeLine");
						Editor editor = prefs.edit();
						editor.putString(ALREADY_POSTED_KEY, ALREADY_POSTED_KEY_YES);
						editor.commit();
						/*
						 * Toast.makeText(MainActivity.this
						 * .getApplicationContext(), postId,
						 * Toast.LENGTH_LONG).show();
						 */
					}
				}
			};

			Request request = new Request(Session.getActiveSession(),
					"me/feed", postParams, HttpMethod.POST, callback);

			RequestAsyncTask task = new RequestAsyncTask(request);
			task.execute();
		}
		
	}
	
	public static boolean checkAndRestoreFacebookLogin(Context context,Bundle savedInstanceState,Session.StatusCallback statusCallback){
		Session session = Session.getActiveSession();
        Log.i("Ravi","checkFacebookLogin:session = "+session);
        if (session == null) {
        	Log.i("Ravi","savedInstanceState = "+savedInstanceState);
            if (savedInstanceState != null) {
                session = Session.restoreSession(context, null, statusCallback, savedInstanceState);
            }
            if (session == null) {
            	Log.i("Ravi","Creating New Session");
                session = new Session(context);
            }
            Session.setActiveSession(session);
            
            Log.i("Ravi","session.getState() = "+session.getState());
            if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
                session.openForRead(new Session.OpenRequest((Activity)context).setCallback(statusCallback));
            }
            
            
            
           
        }

        return session.isOpened();
	}
	
	
	
	public static void printShaSignatureForFacebook(Context context){
		try {
            PackageInfo info = context.getPackageManager().getPackageInfo(
                  "com.next.aappublicapp", PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) 
                {
                   MessageDigest md = MessageDigest.getInstance("SHA");
                   md.update(signature.toByteArray());
                   Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
                }
        } catch (NameNotFoundException e) {
        } catch (NoSuchAlgorithmException e) {
        }
	}
}
